package com.harmony.pilot.agent.service;

import com.harmony.pilot.agent.model.*;
import com.harmony.pilot.agent.service.LLMServiceClient;
import com.harmony.pilot.common.dto.LLMRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AgentCoreService {
    
    private final LLMServiceClient llmServiceClient;
    private final ConversationManager conversationManager;
    private final ToolRouter toolRouter;
    private final IntentAnalyzer intentAnalyzer;
    
    public AgentCoreService(
            LLMServiceClient llmServiceClient,
            ConversationManager conversationManager,
            ToolRouter toolRouter,
            IntentAnalyzer intentAnalyzer) {
        this.llmServiceClient = llmServiceClient;
        this.conversationManager = conversationManager;
        this.toolRouter = toolRouter;
        this.intentAnalyzer = intentAnalyzer;
    }
    
    public AgentResponse processUserMessage(String sessionId, String userMessage) {
        log.info("Processing user message for session: {}", sessionId);
        
        try {
            // 1. 获取对话上下文
            Conversation conversation = conversationManager.getConversation(sessionId);
            
            // 2. 更新对话历史
            conversation.addMessage(Message.user(userMessage));
            conversation.setState(AgentState.ANALYZING);
            conversationManager.saveConversation(conversation);
            
            // 3. 分析用户意图
            Intent intent = intentAnalyzer.analyze(userMessage, conversation.getContext());
            log.info("Detected intent: {}", intent.getType());
            
            // 4. 选择并执行工具
            AgentTool tool = toolRouter.selectTool(intent, conversation.getContext());
            ToolResult toolResult = null;
            ToolCall toolCall = null;
            
            if (tool != null) {
                conversation.setState(AgentState.EXECUTING);
                conversationManager.saveConversation(conversation);
                
                ToolRequest request = ToolRequest.builder()
                    .toolName(tool.getName())
                    .context(conversation.getContext())
                    .userMessage(userMessage)
                    .parameters(extractToolParameters(userMessage, intent))
                    .build();
                
                toolResult = tool.execute(request);
                
                // 记录工具调用
                toolCall = ToolCall.builder()
                    .toolName(tool.getName())
                    .parameters(request.getParameters())
                    .result(toolResult)
                    .timestamp(java.time.LocalDateTime.now())
                    .status(toolResult.isSuccess() ? 
                        ToolCall.ToolStatus.SUCCESS : ToolCall.ToolStatus.FAILED)
                    .build();
                conversation.getToolCalls().add(toolCall);
            }
            
            // 5. 生成回复
            conversation.setState(AgentState.GENERATING);
            conversationManager.saveConversation(conversation);
            
            String response = generateResponse(conversation, toolResult, userMessage);
            
            // 6. 更新对话
            conversation.addMessage(Message.assistant(response));
            conversation.setState(AgentState.IDLE);
            conversationManager.saveConversation(conversation);
            
            // 7. 构建响应
            AgentResponse agentResponse = AgentResponse.builder()
                .message(response)
                .toolCalls(conversation.getToolCalls())
                .codeChanges(extractCodeChanges(toolResult))
                .suggestions(generateSuggestions(intent, toolResult))
                .build();
            
            return agentResponse;
                
        } catch (Exception e) {
            log.error("Error processing user message", e);
            Conversation conversation = conversationManager.getConversation(sessionId);
            conversation.setState(AgentState.ERROR);
            conversationManager.saveConversation(conversation);
            
            return AgentResponse.builder()
                .message("抱歉，处理您的请求时出现了错误: " + e.getMessage())
                .build();
        }
    }
    
    private Map<String, Object> extractToolParameters(String userMessage, Intent intent) {
        Map<String, Object> params = new HashMap<>();
        // 根据意图提取参数
        if (intent.getParameters() != null) {
            params.putAll(intent.getParameters());
        }
        return params;
    }
    
    private String generateResponse(Conversation conversation, ToolResult toolResult, String userMessage) {
        try {
            StringBuilder prompt = new StringBuilder();
            
            // 系统提示
            prompt.append("你是一个专业的OpenHarmony开发助手。")
                  .append("请根据工具执行结果，生成友好、专业的回复。\n\n");
            
            // 对话历史
            prompt.append("对话历史：\n");
            for (Message msg : conversation.getRecentMessages(5)) {
                prompt.append(msg.getRole()).append(": ").append(msg.getContent()).append("\n");
            }
            
            // 工具结果
            if (toolResult != null) {
                prompt.append("\n工具执行结果：\n");
                prompt.append(toolResult.getMessage()).append("\n");
                if (toolResult.getData() != null) {
                    prompt.append("数据：").append(toolResult.getData()).append("\n");
                }
            }
            
            prompt.append("\n请生成回复：");
            
            String systemPrompt = "你是一个专业的OpenHarmony开发助手，善于用简洁明了的语言解释技术问题。";
            String response = llmServiceClient.generate(prompt.toString(), systemPrompt);
            
            if (response != null && !response.isEmpty()) {
                return response;
            }
        } catch (Exception e) {
            log.error("Failed to generate response with LLM", e);
        }
        
        return generateSimpleResponse(toolResult, userMessage);
    }
    
    private String generateSimpleResponse(ToolResult toolResult, String userMessage) {
        if (toolResult == null) {
            return "我理解您的需求，但暂时无法处理。请稍后再试或联系管理员。";
        }
        
        if (toolResult.isSuccess()) {
            return toolResult.getMessage() != null ? 
                toolResult.getMessage() : "操作执行成功。";
        } else {
            return "操作执行失败: " + (toolResult.getError() != null ? 
                toolResult.getError() : "未知错误");
        }
    }
    
    private List<ConversationContext.CodeChange> extractCodeChanges(ToolResult toolResult) {
        List<ConversationContext.CodeChange> changes = new ArrayList<>();
        if (toolResult != null && toolResult.getData() != null) {
            // 从工具结果中提取代码变更
            // 具体实现取决于工具返回的数据格式
            if (toolResult.getData() instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> data = (Map<String, Object>) toolResult.getData();
                if (data.containsKey("codeChanges")) {
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> codeChanges = (List<Map<String, Object>>) data.get("codeChanges");
                    if (codeChanges != null) {
                        for (Map<String, Object> change : codeChanges) {
                            ConversationContext.CodeChange codeChange = ConversationContext.CodeChange.builder()
                                .filePath((String) change.get("filePath"))
                                .type((String) change.get("type"))
                                .content((String) change.get("content"))
                                .line((Integer) change.getOrDefault("line", 0))
                                .build();
                            changes.add(codeChange);
                        }
                    }
                }
            }
        }
        return changes;
    }
    
    private List<String> generateSuggestions(Intent intent, ToolResult toolResult) {
        List<String> suggestions = new ArrayList<>();
        
        if (intent.getType() == Intent.IntentType.CODE_GENERATION && toolResult != null && toolResult.isSuccess()) {
            suggestions.add("是否需要生成单元测试？");
            suggestions.add("是否需要更新BUILD.gn文件？");
            suggestions.add("是否需要提交代码？");
        }
        
        if (intent.getType() == Intent.IntentType.TEST_GENERATION && toolResult != null && toolResult.isSuccess()) {
            suggestions.add("是否需要运行测试？");
            suggestions.add("是否需要更新BUILD.gn文件？");
        }
        
        return suggestions;
    }
}

